
(function ($){
    var clientCode,captchaImg,captcha,userName,password;
    function start(){
        clientCode = $("#clientCode");
        captchaImg = $("#captchaImg");
        captcha = $("#captcha");
        userName = $('[name="userName"]');
        password = $('[name="password"]');


        getCaptchaImg();
        bindEvent();
    }

    function getCaptchaImg(){
        var code = new Date().getTime();
        captcha.val("");
        clientCode.val(code);
        captchaImg.attr("src",base_url + "/captcha/login?clientCode="+code);
    }

    function clearPassword(){
        password.val("");
        getCaptchaImg();
    }

    function bindEvent(){

        captchaImg.on("click",function (){
            getCaptchaImg();
        });


        // login Form Valid
        var loginFormValid = $("#loginForm").validate({
            errorElement : 'span',
            errorClass : 'help-block',
            focusInvalid : true,
            rules : {
                userName : {
                    required : true
                },
                password : {
                    required : true
                } ,
                captcha : {
                    required : true
                }
            },
            messages : {
                userName : {
                    required  : "请输入用户名"
                },
                password : {
                    required  : "请输入密码"
                },
                captcha : {
                    required  : "请输入验证码"
                }
            },
            highlight : function(element) {
                $(element).closest('.form-group').addClass('has-error');
            },
            success : function(label) {
                label.closest('.form-group').removeClass('has-error');
                label.remove();
            },
            errorPlacement : function(error, element) {
                element.parent('div').append(error);
            },
            submitHandler : function(form) {
                taotaoLink.post(base_url + "/user/login", {
                    userName :userName.val(),
                    password : password.val() ,
                    clientCode : clientCode.val() ,
                    captcha : captcha.val()
                }, {
                    succMsg:"登录成功",
                    succCallback:function(data, status) {
                        window.location.href = base_url + "/index";
                    },
                    errCallback:function(data, status) {
                        clearPassword();
                    }
                });
            }
        });

    }

    $(function(){
        start();
    });



})(jQuery);




